var express = require("express");
var router = express.Router();
var { user } = require("../model/model");
const multiparty = require("multiparty");
const { sendCode, randomCode } = require("../tools/sendCode");
const jwt = require("jsonwebtoken");
const nodemailer = require("nodemailer"); //发送邮件

//人脸识别
var AipFaceClient = require("baidu-aip-sdk").face;
var HttpClient = require("baidu-aip-sdk").HttpClient;
HttpClient.setRequestOptions({ timeout: 5000 });
// 设置APPID/AK/SK
const APP_ID = "116144819";
const API_KEY = "Zt8cNV1HLbS27LpNkEoE8SZM";
const SECRET_KEY = "P3U5jv24GMIeeCx97KsxxfXHhI7TINhf";
// 新建一个对象，建议只保存一个对象调用服务接口
var client = new AipFaceClient(APP_ID, API_KEY, SECRET_KEY);

let faceVerificationWithLiveness = async (image) => {
  try {
    const detectResult1 = await client
      .faceverify([
        {
          image: image,
          image_type: "BASE64",
        },
      ])
      .then(function (result) {
        return result;
      });

    const isLive1 =
      detectResult1 &&
      detectResult1.result &&
      detectResult1.result.face_list &&
      detectResult1.result.face_list.length > 0 &&
      detectResult1.result.face_liveness > 0.9;
    if (!isLive1) {
      console.log("活体检测失败");
      return 400;
    }
    var imageType = "BASE64";
    var groupIdList = "A1";
    //调用人脸搜索
    const detectResult2 = await client
      .search(image, imageType, groupIdList)
      .then(function (result) {
        return result;
      })
      .catch(function (err) {
        // 如果发生网络错误
        console.log(err);
      });
    if (
      detectResult2.error_code === 0 &&
      detectResult2.result.user_list[0].score > 80
    ) {
      console.log("人脸验证成功");
      return 200;
    } else {
      console.log("人脸验证失败");
      return 402;
    }
  } catch (err) {
    console.error("人脸验证或活体检测过程中发生错误:", err);
    return 500;
  }
};
router.post("/face-verification", async (req, res) => {
  const { faceData } = req.body;
  await faceVerificationWithLiveness(faceData).then((code) => {
    console.log(code);
    if (code === 200) {
      res.send({
        code: 200,
        message: "人脸验证成功",
      });
    } else if (code === 400) {
      res.send({
        code: 400,
        message: "活体检测失败",
      });
    } else if (code === 402) {
      res.send({
        code: 402,
        message: "人脸验证失败",
      });
    }
  });
});

/* 登录. */
const secretKey = "your_secret_key"; // 密钥，实际应用中应从环境变量读取
router.post("/login", async (req, res) => {
  const { admin, password } = req.body;
  const result = await user.findOne({ admin, password });

  console.log(result);
  if (result) {
    // 生成访问令牌和刷新令牌
    const accessToken = jwt.sign({ userId: user.id }, secretKey, {
      expiresIn: "15m",
    });
    const refreshToken = jwt.sign({ userId: user.id }, secretKey, {
      expiresIn: "7d",
    });
    res.send({
      code: 200,
      message: "登录成功",
      data: result,
      accessToken,
      refreshToken,
    });
  }
});

//上传图片
router.post("/upload", (req, res) => {
  const form = new multiparty.Form();
  form.uploadDir = "upload";
  form.parse(req, (err, fields, files) => {
    console.log(files);
    if (err) {
      console.log(err);
      res.send({
        code: 500,
        message: "上传失败",
      });
    } else {
      res.send({
        code: 200,
        message: "上传成功",
        data: "http://localhost:3000/" + files.file[0].path,
      });
    }
  });
});

//注册
router.post("/zhuce", async (req, res) => {
  const { admin, password, phone, email, landlord } = req.body;
  const result = await user.create({ admin, password, phone, email, landlord });
  console.log(result);
  if (result) {
    res.send({
      code: 200,
      message: "注册成功",
      data: result,
    });
  }
});

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

var code = ""; //定义一个全局变量来存储验证码
// 验证码(这只是一个获取验证码的接口)
router.post("/SMS", async (req, res) => {
  let { phone } = req.body;
  console.log(phone);
  let code = randomCode(4); //生成6位数字随机验证码
  console.log(code);
  sendCode(phone, code, function (success) {
    if (success) {
      console.log(code);
      res.send({
        code: 200,
        msg: "验证码发送成功",
        data: code,
      });
    } else {
      res.send("短信验证码发送失败");
    }
  });
});

//登录的话还是需要在前端将验证码和手机号发送到后端，然后后端再进行验证
router.post("/phoneLogin", async (req, res) => {
  const { phone, codes } = req.body;
  console.log(req.body);
  const result = await user.findOne({ phone });
  console.log(result);
  if (result || codes === code) {
    res.send({
      code: 200,
      message: "登录成功",
      data: result,
    });
  }
});

let codee = "";

// 邮箱验证
router.post("/email", async (req, result) => {
  let { email } = req.body;
  console.log(req.body);
  // console.log(req.body);
  let code = randomCode(6); //生成6位数的验证码
  codee = code;
  //开启一个 SMTP 连接池
  var transport = nodemailer.createTransport({
    host: "smtp.qq.com", //QQ邮箱的 smtp 服务器地址
    secure: true, //使用 SSL 协议
    secureConnection: false, //是否使用对 https 协议的安全连接
    port: 465, //QQ邮件服务所占用的端口
    auth: {
      user: "2365766885@qq.com", //开启 smtp 服务的发件人邮箱，用于发送邮件给其他人
      pass: "cpfgaqvyacobeafb", //SMTP 服务授权码
    },
  });
  //邮箱配置
  var mailOption = {
    from: "2365766885@qq.com", //发件人
    to: email, //收件人
    subject: "验证码", //标题
    html: `<b>验证码为：${code}</br>请在5分钟之内完成验证</b>`, //正文，可使用 HTML 格式进行渲染
  };
  //发送邮件
  transport.sendMail(mailOption, (err, res) => {
    if (err) {
      //执行错误
      result.send({
        state: 400,
        msg: "发送失败,请检查邮箱是否正确",
      });
    } else {
      result.send({
        state: 200,
        msg: "发送成功",
        code,
      }); //执行成功， 会返回响应体内容。
    }
    transport.close(); // 如果没用，则关闭连接池
  });
});

//登录的话还是需要在前端将验证码和email发送到后端，然后后端再进行验证
router.post("/phoneLogin", async (req, res) => {
  const { email, codes } = req.body;
  console.log(req.body);
  const result = await user.findOne({ email });
  console.log(result);
  if (result || codee === codes) {
    res.send({
      code: 200,
      message: "登录成功",
      data: result,
    });
  }
});
module.exports = router;
